<?php
// +----------------------------------------------------------------------
// | 商城模块
// +----------------------------------------------------------------------

namespace app\mall\model;

use think\Model as ThinkModel;
use think\facade\Db;

/**
 * 授权码模型
 * @package app\mall\model
 */
class Token extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mall_token';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
	
	// 错误信息
	protected $error;
	
    /**
     * 获取指定Token数据
     * @param int $type Token类型
     * @return mixed|static
     */
    public function getInfo($type = '')
    {
		if ($type == '') {
			$this->error = 'Token类型必须传入';
			return false;
		}
        $result = cache('token_'. $type);
        if (!$result) {
			$time = time();
            $result = self::where('type', '=', $type)
					->where('expire_time', '>', $time)
					->order('id desc')
					->find();	
			if (!$result) {
				$this->error = 'expired';
				return false;
			}
			$result = $result->visible(['access_token','expire_time'])->toJson();
			$result = json_decode($result); //返回对象实例
            // 非开发模式，缓存数据
            if (config('app.develop_mode') == 0) {
				$cache_time = $result->expire_time - $time;
                cache('token_'. $type, $result, $cache_time);
            }
			// 清除已过期的token
			self::where('expire_time', '<', $time)->delete();
        }
        return $result;
    }
	
	/**
	 * Token类型
	 * @param int $id 类型id
	 * @author paulxun
	 * @return array|static
	 */
	public static function types($id = 99)
	{
		$types = [
			'elind'		=> '智联云',
			'wechat' 	=> '微信平台',
			'speaker'	=> '立通智联',
		];
	    if ($id === 99) {
	        $result = $types;
	    }else{
			$result = '';
			if(isset($types[$id])) $result = $types[$id];
		}
	    return $result;
	}
	
	/**
	 * 获取错误信息
	 * @access public
	 * @return mixed
	 */
	public function getError()
	{
	    return $this->error;
	}
}